package com.opennetexam.manager.bussinessservice;

import com.opennetexam.manager.common.CacheKey;
import com.opennetexam.manager.common.OperationResult;
import com.opennetexam.manager.common.ReturnData;
import com.opennetexam.manager.databasemodel.*;
import com.opennetexam.manager.dto.ClientLoginModel;
import com.opennetexam.manager.dto.ExamAdminInfoDTO;
import com.opennetexam.manager.dto.ExaminerSubjectInfoDTO;
import com.opennetexam.manager.dto.LoginVo;
import com.opennetexam.manager.enums.DeploymentMode;
import com.opennetexam.manager.enums.ExamPlanSysState;
import com.opennetexam.manager.enums.LoginResultType;
import com.opennetexam.manager.enums.OperationResultType;
import com.opennetexam.manager.mapper.ExamPlanInfoMapper;
import com.opennetexam.manager.mapper.ExamSubjectMapper;
import com.opennetexam.manager.mapper.ExamineeMapper;
import com.opennetexam.manager.service.ExamAdminUserService;
import com.opennetexam.manager.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author 奶茶
 * Created by on 2018/11/4 10:25.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WANExamBusinessService {

    @Autowired
    private ExamineeMapper examineeMapper;
    @Autowired
    private ExamSubjectMapper examSubjectMapper;
    @Autowired
    private ExamPlanInfoMapper examPlanInfoMapper;
    @Autowired
    private ExamAdminUserService adminUserService;


    @Value("${TestMode}")
    private Integer testMode;

    /**
     * 考生登录逻辑
     * @param examCardNo
     * @param passWord
     * @return
     */
    public LoginVo examinerLoginBussines(String examCardNo,String passWord){
        //校验用户名 密码
        Examinee examiner = this.getExaminer(examCardNo, passWord);
        if (examiner == null) {
            return new LoginVo(LoginResultType.EXAMCARDNO_IS_INVALID.getPrefix());
        }

        String cacheKey = null;
        //将考生基本信息写入缓存
        if(testMode.equals(DeploymentMode.WAN_Deployment.getPrefix())){
            cacheKey =  CacheKey.getExaminerLoginInfoKey(examiner.getExamPlanInfoID(),examiner.getExamineeID(),DeploymentMode.WAN_Deployment.getPrefix());
            ClientLoginModel clientLoginModel = new ClientLoginModel();
            clientLoginModel.setExaminee(examiner);
            RedisUtil.setValue(cacheKey,GsonUtil.toJson(clientLoginModel),21600);
            return new LoginVo(LoginResultType.JUMP_FREE_EXAM.getPrefix(),cacheKey);
        }else{
            return new LoginVo(LoginResultType.DEPLOYMENTMODE_ERROR.getPrefix(),cacheKey);
        }
    }

    /**
     * 玩靠管理端登录
     * @param account
     * @param passWord
     * @return
     */
    public OperationResult examAdminUserLogin(String account,String passWord){
        OperationResult operationResult = new OperationResult();
        String value = RedisUtil.getValue(account);
        if(!StringUtils.isEmpty(value)){
            RedisUtil.setValue(account,value,1800);
            operationResult.setResultType(OperationResultType.Success);
            operationResult.setMessage(OperationResultType.Success.getDisplay());
        }else{
            ExamAdminInfoDTO examAdminUser = adminUserService.getExamAdminUser(account);
            if(examAdminUser != null){
                if(examAdminUser.getPassword().equalsIgnoreCase(AESUtils.encrypt(passWord).trim())){
                    RedisUtil.setValue(examAdminUser.getAccount(),GsonUtil.toJson(examAdminUser),1800);
                    operationResult.setResultType(OperationResultType.Success);
                    operationResult.setMessage(OperationResultType.Success.getDisplay());
                }else{
                    operationResult.setResultType(OperationResultType.Error);
                    operationResult.setMessage("密码错误！");
                }
            }else{
                operationResult.setResultType(OperationResultType.Error);
                operationResult.setMessage("用户信息不存在！");
            }
        }
        return operationResult;
    }

    /**
     * 获取考生科目列表
     * @param token
     * @return
     */
    public ReturnData getSubjectList(String token){
        //获取缓存中的考生信息
        ClientLoginModel cacheValue = getEhCacheValue(token);
        if(cacheValue == null){
            return new ReturnData(true,"缓存信息为空！","-1",null);
        }else{
            Examinee examiner = cacheValue.getExaminee();
            if(examiner == null){
                return new ReturnData(true,"考生信息为空！","-1",null);
            }else{
                //获取基本考生信息
                String examinerID = examiner.getExamineeID();
                String examPlanID = examiner.getExamPlanInfoID();
                return new ReturnData(true,"","1",examSubjectMapper.getExaminerSubjectList(examPlanID, examinerID));
            }
        }
    }

    /**
     * 获取考生是否可以考试
     * @param token
     * @param subjectID
     * @return
     */
    public ReturnData getExamInfo(String token,String subjectID){
        //获取缓存信息
        ClientLoginModel cacheValue = getEhCacheValue(token);
        if(cacheValue == null || cacheValue.getExaminee() == null){
            return new ReturnData(true,"缓存信息为空！","-1",null);
        }else{
            Examinee examinee = cacheValue.getExaminee();
            ExamPlanInfo planInfo = examPlanInfoMapper.getExamPlanInfoBySysState(examinee.getAppID(), examinee.getExamPlanInfoID(), ExamPlanSysState.TestPaperCreated.getPrefix());
            if(planInfo == null){
                return new ReturnData(true,"试卷生成中，请稍后再试！","-1",null);
            }else{
                cacheValue.setExamPlan(planInfo);
                ExaminerSubjectInfoDTO examinerSubjectInfo = examSubjectMapper.getExaminerSubjectInfo(examinee.getExamPlanInfoID(), subjectID, examinee.getExamineeID());

                if(examinerSubjectInfo == null){
                    return new ReturnData(true,"当前时间段内没有可以进行的考试！","-1",null);
                }else{
                    ExamineeArrange examineeArrange = new ExamineeArrange();
                    examineeArrange.setExamineeArrangeID(examinerSubjectInfo.getExamineeArrangeID());
                    examineeArrange.setExamPaperID(examinerSubjectInfo.getExamPaperID());
                    examineeArrange.setExamPlanInfoID(examinerSubjectInfo.getExamPlanInfoID());
                    examineeArrange.setExamSceneID(examinerSubjectInfo.getExamSceneID());
                    examineeArrange.setExamRoomID(examinerSubjectInfo.getExamRoomID());
                    examineeArrange.setExamSubjectID(subjectID);
                    examineeArrange.setPlanBeginTime(examinerSubjectInfo.getPlanBeginTime());

                    ExamSubject examSubject = new ExamSubject();
                    examSubject.setExamSubjectID(examinerSubjectInfo.getExamSubjectID());
                    examSubject.setSubjectName(examinerSubjectInfo.getSubjectName());
                    examSubject.setSubjectCode(examinerSubjectInfo.getSubjectCode());
                    examSubject.setTimeLimits(examinerSubjectInfo.getTimeLimits());

                    cacheValue.setExamArrange(examineeArrange);
                    cacheValue.setExamSubject(examSubject);
                    //更新考生缓存
                    RedisUtil.setValue(token,GsonUtil.toJson(cacheValue),21600);
                    return new ReturnData(true,"","1",null);
                }
            }
        }
    }

    /**
     * 试卷下载页 获取考生信息
     * @param token
     * @return
     */
    public ReturnData getExaminerInfoFromCache(String token){
        ClientLoginModel cacheValue = getEhCacheValue(token);
        if(cacheValue == null || cacheValue.getExaminee() == null){
            return new ReturnData(true,"考生信息为空！","-1",null);
        }else{
            Examinee examinee = cacheValue.getExaminee();
            examinee.setPassword(null);
            return new ReturnData(true,"","1",examinee);
        }
    }

    /**
     * 获取当前计划的登录模式
     * @param token
     * @return
     */
    public Integer getLoginMode(String token){
        ClientLoginModel cacheValue = getEhCacheValue(token);
        if(cacheValue == null || cacheValue.getExamPlan() == null){
            return -1;
        } else{
            return cacheValue.getExamPlan().getLoginMode();
        }
    }


    /**
     * 考生登录 校验用户名 密码
     * @param examCardNo
     * @param passWord
     * @return
     */
    private Examinee getExaminer(String examCardNo,String passWord) {
        passWord = AESUtils.encrypt(passWord).trim();
        return examineeMapper.getExaminerByCardNo(examCardNo.toUpperCase(),passWord);
    }


    /**
     * 获取缓存
     * @param token
     * @return
     */
    private ClientLoginModel getEhCacheValue(String token){
        //获取缓存数据
        Map<String,Object> info = null;
        if( PatternUtil.getPatternSplit(token,":").size() > 1){
            info =  GsonUtil.fromJsonToMap(RedisUtil.getValue(token));
            return  GsonUtil.fromJsonToObject(GsonUtil.toJson(info), ClientLoginModel.class);
        }
        return null;
    }

    public static void main(String[] args) {
        String encrypt = AESUtils.encrypt("Aa123456");
        System.out.println(encrypt);
    }

}
